using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Soft2ApiDemo.Domain.Entity;
using Soft2ApiDemo.Domain.Repository;

namespace Soft2ApiDemo.Infrastructure.Filters
{
    public class MyGlobalExceptionFilter : IAsyncExceptionFilter
    {
        private readonly IRepositoryBase<AppLogs> _logsRes;

        public MyGlobalExceptionFilter(IRepositoryBase<AppLogs> logsRes){
            _logsRes=logsRes;
        }

        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                string msg = context.Exception.Message;
                _logsRes.Add(new AppLogs{
                    Message=msg,
                    Exception=context.Exception.ToString()
                });

                context.Result =
                    new ContentResult {
                        Content = msg,
                        StatusCode = 200,
                        ContentType = "text/html;charset=utf-8"
                    };
            }
            context.ExceptionHandled = true; //异常已处理了

            return Task.CompletedTask;
        }
    }
}
